package com.xianggu.mybatis.configFile;


import com.xianggu.mybatis.enums.MysqlConnectParam;
import com.xianggu.mybatis.utils.ObjectTranUtils;

import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class PropertyReader implements FileReaderStrategy {
    private static Properties properties;

    static {
        properties = new Properties();
        try {
            // 假设配置文件名为config.properties，位于resources目录下
            InputStream inputStream = PropertyReader.class.getClassLoader().getResourceAsStream("config.properties");
            if (inputStream!= null) {
                properties.load(inputStream);
            } else {
                throw new IOException("config.properties not found in resources");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static String getProperty(String key) {
        return properties.getProperty(key);
    }
    public static Map<String, Object> getPropertyMap() {
        Map<String, Object> resultMap = new HashMap<>(properties.size());
        for (Object key : properties.keySet()) {
            Object value = properties.get(key);
            // 添加元素
            resultMap.put(key.toString(), value);
        }
        return resultMap;
    }

    public static void main(String[] args) {
        for (Object key : properties.keySet()) {
            Object value = properties.get(key);
            System.out.println(key + " = " + value);
        }

        String url = getProperty("url");
        String username = getProperty("username");
        String password = getProperty("password");
        String driverClassName = getProperty("driver - class - name");
        System.out.println("URL: " + url);
        System.out.println("Username: " + username);
        System.out.println("Password: " + password);
        System.out.println("Driver Class Name: " + driverClassName);
    }

    @Override
    public MysqlConnectParam readFile() throws IOException {
        URL resource = super.getClass().getClassLoader().getResource("config.properties");

        // 找不到文件则跳过该策略
        if(resource == null) {
            return null;
        }

        File file = new File(resource.getFile());
        if (file.exists()) {
            // 这里可以添加实际的读取文件内容的代码，简单返回一个标识
             properties.load(resource.openStream());
            MysqlConnectParam connectParam = ObjectTranUtils.MapToObject(MysqlConnectParam.class, getPropertyMap());
            connectParam.setDriverClassName(getProperty("driver-class-name"));
            connectParam.setInitialSize(Integer.parseInt(getProperty("initial-size")));
            connectParam.setMinIdle(Integer.parseInt(getProperty("min-idle")));

            return connectParam;
        }
        return null;
    }
}